package com.zhangpingyang.jwttoken.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Zhang Pingyang
 * @Date: 2019/11/8 17:45
 */
@Component
public class JwtTokenUtil {
    private final static String CLAIM_KEY_USERNAME = "sub";
    private final static String CLAIM_KEY_CREATED = "created";
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private long expiration;

    private byte[] b;

    @PostConstruct
    private void init() {
        System.out.println("init() execute");
    }

    public String generatorToken(UserDetails userDetails) {
        Map<String, Object> map = new HashMap<>();
        map.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        map.put(CLAIM_KEY_CREATED, new Date());
        return this.generatorToken(map);

    }

    public String getUsernameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUsernameFromToken(token);
        if (username == null) {
            return false;
        }
        return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
    }

    private boolean isTokenExpired(String token) {
        Date expireDate = getExpireDateFromToken(token);
        return new Date().after(expireDate);
    }

    private Date getExpireDateFromToken(String token) {
        return getClaimFromToken(token).getExpiration();
    }

    /**
     * 生成token
     */
    private String generatorToken(Map<String, Object> claim) {
        return Jwts.builder()
                .setClaims(claim)
                .setExpiration(generatorExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 从token中获取jwt的负载
     */
    private Claims getClaimFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    private Date generatorExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration);
    }

}
